package net.xuele.learn.rsocket;

import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import reactor.core.Disposable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: patrick-Hikari
 * @description:
 * @date: 2021/8/19 10:07 上午
 */
@Slf4j
public class RSocketTest {
    private static Server server;

    public RSocketTest() {
    }

    @BeforeClass
    public static void setUp() {
        server = new Server();
    }

    @AfterClass
    public static void tearDown() {
        server.dispose();
    }

    @Test
    public void whenSendingAString_thenRevceiveTheSameString() {
        ReqResClient client = new ReqResClient();
        String param = "hello";

        System.out.println(client.callBlocking(param));

        client.dispose();
    }

    /**
     * 当前的这个测试场景下，fireAndForget往服务端发消息
     */
    @Test
    public void whenSendingStream_thenReceiveTheSameStream() {
        // 创建客户端，推送数据到server，并且已经开始发送了
        FireNForgetClient client = new FireNForgetClient();
        // 创建客户端，从服务端读取数据流，并且订阅事件
        ReqStreamClient streamClient = new ReqStreamClient();
        // 获取客户端将要发送的数据
        List<Float> data = client.getData();
        // 存储结果
        List<Float> dataReceived = new ArrayList<>();

        // 校验收到的数据是否和发送的数据一致
        Disposable subscribe = streamClient.getDataStream()
                .index()
                .subscribe(
                        tuple -> {
                            Assert.assertEquals("wrong value", data.get(tuple.getT1().intValue()), tuple.getT2());
                            dataReceived.add(tuple.getT2());
                        },
                        err -> {
                            log.error(err.getMessage());
                        }
                );
        // 发送数据
        client.sendData();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        subscribe.dispose();
        client.dispose();

        Assert.assertEquals("wrong count received", data.size(), dataReceived.size());
    }


    @Test
    public void whenRunningChannelGame_thenLogTheResults() {
        ChannelClient client = new ChannelClient();
        client.playGame();
        client.dispose();
    }
}
